﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using UniCT.LinkShareWpf.Interface;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.Drawing;
using UniCT.LinkShareWpf.Model;
using LinkShareWpf.Properties;


namespace UniCT.LinkShareWpf.CommunicationChannel
{
    public class Contract : IContract
    {
        // Ogni volta che il client invoca un metodo del contratto viene creata una nuova istanza della classe
        // perciò per mantenere uno stato abbiamo la necessità di creare la lista statica

        static LinkedList<Guid> netFilterList = new LinkedList<Guid>();
        
        public void SendResource(NetResource netResource)
        {
            Console.WriteLine("Server, Ricevuta risorsa da : " + netResource.Sender.ToString());
            MyTempResourcesList.Instance.AddResource(netResource);
        }

        public void SearchRequest(NetFilter netFilter)
        {
            if (!netFilterList.Contains(netFilter.Id))
            {
                netFilterList.AddFirst(netFilter.Id);
                Console.WriteLine("Server, ho ricevuto un netFilter con Sorgente. " + netFilter.Sender.ToString());
                Console.WriteLine("TTL: " + netFilter.TTL);
                ObservableCollection<Resource> tempRes = netFilter.FilterResources( MyResources.Instance.Resources);

                foreach (Resource res in tempRes)
                {
                    NetResource netResource = new NetResource(res);
                    netResource.Id = netFilter.Id;
                    netResource.SetImageBuffer();
                    Client clientToSender = new Client(netFilter.Sender);
                    clientToSender.SendResourceRequest(netResource);
                 }
                netFilter.DeHop();
     
                netFilter.Nodes.AddFirst(Settings.Default.UriServer);
                if (netFilter.TTL > 0)
                    foreach (Node node in MyNode.Instance.Nodes)
                        if (!netFilter.Nodes.Contains(node.Uri) && node.Uri!=netFilter.Sender)
                        {
                            Client client = new Client(node.Uri);
                            client.SingleRequest(netFilter);
                        }
            }
            else
                Console.WriteLine("Server, ho rigettato una ricerca gia consumata");
        }

        public long Ping(long tick)
        {
            Console.WriteLine("Server, ho ricevuto un ping.");
            return tick;
        }

    }

}
